﻿using System.Security.Claims;
using AutoMapper;
using MediatR;
using Provenance.ErrorCount;
using Provenance.Infra.Interfaces.User;
using Provenance.Read.Api.Application.Command.User;
using Provenance.Read.Api.Dto.User;

namespace Provenance.Read.Api.Application.CommandHandler.User
{
    public class GetTreePermissionListCommandHandler : IRequestHandler<GetTreePermissionListCommand, ApiResult<IList<GetTreePermissionListResponseDTO>>>
    {
        private readonly IPermissionRepository _permissionRepository;
        private readonly IUserRoleRepository _userRoleRepository;
        private readonly IRolePermissionRepository _rolePermissionRepository;
        private readonly ILogger<GetTreePermissionListCommandHandler> _logger;
        private readonly IMapper _mapper;
        private readonly IHttpContextAccessor _httpContextAccessor;
        public GetTreePermissionListCommandHandler(IPermissionRepository permissionRepository, ILogger<GetTreePermissionListCommandHandler> logger, IMapper mapper, IUserRoleRepository userRoleRepository, IRolePermissionRepository rolePermissionRepository, IHttpContextAccessor httpContextAccessor)
        {
            _permissionRepository = permissionRepository;
            _logger = logger;
            _mapper = mapper;
            _userRoleRepository = userRoleRepository;
            _rolePermissionRepository = rolePermissionRepository;
            _httpContextAccessor = httpContextAccessor;
        }
        public async Task<ApiResult<IList<GetTreePermissionListResponseDTO>>> Handle(GetTreePermissionListCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var list = await GetTree();
                var user = _httpContextAccessor.HttpContext.User;
                var UserId = user.FindFirst(type: ClaimTypes.NameIdentifier)?.Value;
                //当前用户对应的权限ID
                var userRoles=await _userRoleRepository.GetAllAsync(x => x.UserId == int.Parse(UserId) && x.IsDeleted==false);
                var roleIds=userRoles.Select(x=>x.RoleId).ToArray();
                var userPermissions=await _rolePermissionRepository.GetAllAsync(x => roleIds.Contains(x.RoleId)&&x.IsDeleted==false);
                var PermissionIds=userPermissions.Select(x=>x.PermissionId).ToArray();
                //过滤出当前用户的权限
                list = list.Where(x => PermissionIds.Contains(x.PermissionId)).ToList();

                return ApiResult<IList<GetTreePermissionListResponseDTO>>.Success(list);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting permission list" + ex.Message);
                return ApiResult<IList<GetTreePermissionListResponseDTO>>.Failure("Error getting permission list" + ex.Message);
            }
        }
        public async Task<IList<GetTreePermissionListResponseDTO>> GetTree(int parentId = 0)
        {
            var Tree = await _permissionRepository.GetAllAsync(x => x.ParentId == parentId);
            var result = _mapper.Map<IList<GetTreePermissionListResponseDTO>>(Tree);
            foreach (var item in result)
            {
                item.Children = await GetTree(item.PermissionId);
            }
            return result;
        }



    }
}
